package cn.mw.cmdb.view;

import cn.mw.cmdb.entity.AssetsScanResultInfo;
import cn.mw.cmdb.entity.ScanResultFailInfo;
import cn.mw.cmdb.entity.ScanResultSuccessInfo;
import cn.mw.cmdb.param.AssetsInstanceScanSearchParam;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.components.mongodb.page.MWPage;
import org.springframework.util.StringUtils;

import java.util.List;

public class AssetsScanResultInfoConverter implements ViewConvert<AssetsScanResultInfo , AssetsScanResultInfo>{
    public static String SearchParamKey = "AssetsScanResultSearchParam";
    private String successSign = "success";

    private String failSign = "fail";
    @Override
    public AssetsScanResultInfo convert(AssetsScanResultInfo assetsScanResultInfo, ViewConvertContext context) throws Exception {
        AssetsInstanceScanSearchParam searchParam = (AssetsInstanceScanSearchParam)context.get(SearchParamKey);
        String queryIdent = searchParam.getQueryIdent();
        MWPage mwPage = searchParam.getPage();
        mwPage.setTotal(-1);
        if(!StringUtils.hasText(queryIdent) || successSign.equals(queryIdent)){
            List<ScanResultSuccessInfo> ret = process(assetsScanResultInfo.getSuccessList() ,ScanResultSuccessInfo.class ,searchParam);
            assetsScanResultInfo.setSuccessList(ret);
            assetsScanResultInfo.setFailList(null);
        }else{
            List<ScanResultFailInfo> ret = process(assetsScanResultInfo.getFailList() ,ScanResultFailInfo.class ,searchParam);
            assetsScanResultInfo.setFailList(ret);
            assetsScanResultInfo.setSuccessList(null);
        }

        return assetsScanResultInfo;
    }

    private <T> List<T> process(List<T> datas ,Class<T> tClass ,AssetsInstanceScanSearchParam searchParam){
        List<T> ret = null;
        if (null != searchParam && null != searchParam.getPage()) {
            MWPage mwPage = searchParam.getPage();
            //如果没有设置总数,说明list的大小为总数
            if (mwPage.getTotal() < 0) {
                int count = (int) datas.size();
                mwPage.setTotal(count);
                int start = (int) CMDBTool.getPageStart(mwPage.getCurrent(), mwPage.getSize());
                int end = start + mwPage.getSize();
                if (end > count) {
                    end = count;
                }
                ret = datas.subList(start, end);
            }
        }
        return ret;
    }
}
